package cn.rongdao.jrkabao.base;

import android.Manifest;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.view.View;

import com.baidu.location.BDLocationListener;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.util.FRLog;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frwidget.dialog.FRDialog;
import com.mifengkong.frwidget.dialog.FRDialogClickListener;

import java.util.HashMap;
import java.util.Map;

import cn.mifengkong.appcommon.locate.LocationService;
import cn.rongdao.jrkabao.App;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.model.LocationModel;
import cn.rongdao.jrkabao.util.permission.GoToPermissionSetting;

/**
 * Created by jiangyongxing on 2017/5/8.
 * 描述：需要百度定位的Activity都可以继承这个类
 */

public abstract class FRBaseNeedLocationActivity extends BaseAutoFinishActivity implements BDLocationListener {

    protected LocationService mLocationService;
    protected double mLatitude;
    protected double mLongitude;
    private static final int ACCESS_LOCATION = 0x101;
    private int targetSdkVersion;

    @Override
    protected void initView() {
        super.initView();
        initLocation();
    }


    private void initLocation() {
        mLocationService = ((App) getApplicationContext()).mLocationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        mLocationService.registerListener(this);
        //注册监听
        int type = getIntent().getIntExtra("from", 0);
        if (type == 0) {
            mLocationService.setLocationOption(mLocationService.getDefaultLocationClientOption());
        } else if (type == 1) {
            mLocationService.setLocationOption(mLocationService.getOption());
        }
    }

    public void startLocate() {
        try {
            final PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
            targetSdkVersion = info.applicationInfo.targetSdkVersion;
            if (!selfPermissionGranted(Manifest.permission.ACCESS_FINE_LOCATION)) {
                ActivityCompat.requestPermissions(thisActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_LOCATION);
            } else {
                startLocation();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean selfPermissionGranted(String permission) {
        boolean result = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (targetSdkVersion >= Build.VERSION_CODES.M) {
                result = ContextCompat.checkSelfPermission(thisActivity(), permission) == PackageManager.PERMISSION_GRANTED;
            } else {
                result = PermissionChecker.checkSelfPermission(thisActivity(), permission) == PermissionChecker.PERMISSION_GRANTED;
            }
        }
        return result;
    }

    public void startLocation(){
        if (mLocationService != null) {
            mLocationService.start();
        }
    }

    public void stopLocate() {
        if (mLocationService != null)
            mLocationService.stop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLocationService != null) {
            mLocationService.unregisterListener(this);
            stopLocate();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        try {
            switch (requestCode) {
                case ACCESS_LOCATION: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        startLocation();
                    } else {
                        showLackPermissionDialog();
                    }
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showLackPermissionDialog() {
        new FRDialog.MDBuilder(thisActivity())
                .setMessage("请去 设置/权限管理 中打开定位权限")
                .setNegativeContentAndListener("知道了", new FRDialogClickListener() {
                    @Override
                    public boolean onDialogClick(View view) {
                        GoToPermissionSetting.GoToSetting(thisActivity());
                        return true;
                    }
                })
                .setNegativeTextColor(ContextCompat.getColor(thisActivity(), R.color.cff5808))
                .show();
    }

    /**
     * 向服务器端发送登录时候的用户的地理位置
     */
    public void sendLocation(String orderNum) {
        if (4.9E-324 == mLatitude || 4.9E-324 == mLongitude || mLatitude == 0 || mLongitude == 0) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("lat", String.valueOf(mLatitude));
        map.put("lng", String.valueOf(mLongitude));
        map.put("order_no", FRString.valueOf(orderNum));
        map.put("code", FRString.isEmpty(orderNum) ? "index" : "create_order");

        LocationModel.getInstance().execute(map, new FRBaseObserver<String>(this) {
            @Override
            protected void onBaseNext(String data) {
                FRLog.error("success to sendLocation");
            }

            @Override
            protected void onBaseError(Throwable t) {
                FRLog.error("failure to sendLocation----" + t.getMessage());
            }
        });
    }
}
